﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShipsLog.Model
{
    public class FolderWatcher: IDisposable
    {
        private System.IO.FileSystemWatcher watcher;

        public event EventHandler<EventArgs<string>> NewFile;

        private System.Collections.Concurrent.ConcurrentDictionary<string, System.Timers.Timer> hotFiles = new System.Collections.Concurrent.ConcurrentDictionary<string, System.Timers.Timer>();

        public FolderWatcher(string path, string filter)
        {
            this.watcher = new System.IO.FileSystemWatcher(path, filter);
            
            this.watcher.Created += watcher_Created;
            this.watcher.Changed += watcher_Changed;

            this.watcher.EnableRaisingEvents = true;

        }

        void watcher_Changed(object sender, System.IO.FileSystemEventArgs e)
        {
            if (this.hotFiles.ContainsKey(e.FullPath))
            {
                this.hotFiles[e.FullPath].Stop();
                this.hotFiles[e.FullPath].Start();
            }            
        }

        void watcher_Created(object sender, System.IO.FileSystemEventArgs e)
        {
            var timer = new System.Timers.Timer(1000);
            timer.AutoReset = false;
            timer.Elapsed += new System.Timers.ElapsedEventHandler((a,b) => this.RaiseNewFile(e.FullPath));
            this.hotFiles[e.FullPath] = timer;
            timer.Enabled = true;
            this.hotFiles[e.FullPath].Start();
        }

        private void RaiseNewFile(string p)
        {
            System.Timers.Timer timer;
            if (this.hotFiles.TryRemove(p, out timer))
            {
                timer.Dispose();
            }

            var tmp = this.NewFile;
            if (tmp != null)
            {
                tmp(this, new EventArgs<string>(p));
            }
        }       
    
        public void Dispose()
        {
 	        this.watcher.Dispose();
            foreach(var timer in this.hotFiles.Values)
            {
                timer.Stop();
                timer.Dispose();
            }
        }
    }
}
